<?php
namespace app\hongbao\controller;

use app\common\library\Sms;
use app\common\model\LihuaOrder;
use app\common\model\LihuaHongbao;
use app\common\model\LihuaUserbonus;
use app\common\model\LihuaWxuser;
use app\common\model\User;
use fast\Random;
use fast\Http;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Exception;
use think\Hook;
use think\Validate;

class Index extends Controller
{
    protected $_error = '';

    // 分享领红包
    public function index()
    {
        if (!$this->request->isMobile()) $this->error('请在手机微信中打开链接', '');

        $oid = $this->request->get('oid');//此oid实为订单号sn
        if (!$oid) $this->error('参数错误', '');
        $order = LihuaOrder::getBySn($oid);
        if (!$order) $this->error('非法操作', '');
        if ($order->create_time < time() - 864000) $this->error('此分享红包已失效');//下单10天后失效

        $uid    = 0;//用户id
        $wxuid  = 0;//微信用户id
        $isget  = 0;//当前用户是否领取红包
        $getcnt = 0;//当前用户今日领取红包次数
        $isover = 0;//当前订单红包是否领完
        $info   = [];//当前用户领取当前红包信息
        $list   = [];//当前订单红包领取列表
        $login  = Cookie::get('lh_h5login');
        if ($login) {
            $login = $this->io_aes_decrypt($login);
            list($uid, $mobile) = explode('|', $login);
            if ($uid && $mobile) {
                $wxuser = LihuaWxuser::get(['user_id' => $uid]);
                if (!$wxuser) {//未绑定微信则重新授权登录
                    Cookie::delete('lh_h5login');
                    $this->redirect($this->request->domain() . '/wxoauth.php?state=' . $oid); exit;
                }

                $getcnt = LihuaHongbao::where(['user_id' => $uid, 'start_date' => date('Y-m-d')])->count();

                // 该订单红包领取列表
                $list = (array)LihuaHongbao::where('order_id', $order->id)->select();
                foreach ($list as $k => $v) {
                    if ($v['user_id'] == $uid) {
                        $isget = 1;//当前用户已领取过
                        $info  = ['reach' => $v['reach'], 'reduce' => $v['reduce'], 'end_date' => $v['end_date']];
                    }
                }
                if (count($list) == 19) $isover = 1;

                // 用户未领取红包则领取
                if ($getcnt < 5 && !$info && $isover == 0) {
                    $moneyArr = [
                        '1',   '1.2', '1.5', '1.6', '1.8', '2',
                        '2.1', '2.2', '2.3', '2.4', '2.5', '3',
                        '4',   '5',   '6',   '7',   '8',   '10'
                    ];
                    $i = mt_rand(0, 17);
                    $money = $moneyArr[$i];
                    if ($money >= 3 && $money < 5) {
                        $reach = $money * 15;
                    } elseif ($money >= 5) {
                        $reach = $money * 20;
                    } else {
                        $reach = 0;
                    }

                    $hb = LihuaHongbao::create([
                        'order_id'   => $order->id,
                        'order_sn'   => $order->sn,
                        'user_id'    => $uid,
                        'nickname'   => $wxuser->nickname,
                        'avatar'     => $wxuser->avatar,
                        'reach'      => $reach,
                        'reduce'     => $money,
                        'start_date' => date('Y-m-d'),
                        'end_date'   => date('Y-m-d', strtotime('+3 day')),
                    ]);
                    array_push($list, $hb->toArray());
                    $info = ['reach' => $reach, 'reduce' => $money, 'end_date' => $hb->end_date];

                    LihuaUserbonus::create([
                        'city_id'    => 0,
                        'user_id'    => $uid,
                        'bonus_id'   => 0,
                        'name'       => '分享红包',
                        'type'       => 9,
                        'reach'      => $reach,
                        'reduce'     => $money,
                        'des'        => '',
                        'start_date' => $hb->start_date,
                        'end_date'   => $hb->end_date,
                    ]);
                }

            } else {
                Cookie::delete('lh_h5login');
                $this->error('非法操作', '');
            }
        } else {
            $wxtk = Cookie::get('lh_wxtk');
            if ($wxtk) {
                $wxtk = base64_decode($wxtk);
                list($access_token, $openid) = explode('|', $wxtk);
                $wxu = $this->getWxUserInfo($access_token, $openid);
                if ($wxu === false) $this->error($this->getError(), '');
                if (!isset($wxu['unionid'])) $this->error('unionid不存在', '');

                $WxUser = LihuaWxuser::get(['unionid' => $wxu['unionid']]);
                if ($WxUser) {
                    $WxUser->nickname = $wxu['nickname'];
                    $WxUser->gender   = $wxu['sex'];
                    $WxUser->province = $wxu['province'];
                    $WxUser->city     = $wxu['city'];
                    $WxUser->avatar   = $wxu['headimgurl'];
                    $WxUser->save();
                } else {
                    $WxUser = LihuaWxuser::create(
                        [
                            'user_id'  => 0,
                            'openid'   => $wxu['openid'],
                            'unionid'  => $wxu['unionid'],
                            'nickname' => $wxu['nickname'],
                            'gender'   => $wxu['sex'],
                            'province' => $wxu['province'],
                            'city'     => $wxu['city'],
                            'avatar'   => $wxu['headimgurl'],
                        ]
                    );
                }
                $wxuid = $WxUser->id;
                Cookie::set('lh_wxuser', $this->io_aes_encrypt($wxuid),
                    ['expire' => 5000, 'secure' => true, 'httponly' => true]);
                // 该订单红包领取列表
                $list = LihuaHongbao::where('order_id', $order->id)->select();
            } else {
                $this->redirect($this->request->domain() . '/wxoauth.php?state=' . $oid); exit;
            }
        }

        $this->assign([
            'uid'     => $uid,
            'wxuid'   => $wxuid,
            'isget'   => $isget,
            'getcnt'  => $getcnt,
            'isover'  => $isover,
            'info'    => $info,
            'list'    => $list,
        ]);
        return $this->fetch();
    }

    // 手机登录
    public function login()
    {
        $mobile  = $this->request->post('phone', '');
        $captcha = $this->request->post('code', '');
        if ($mobile && $captcha) {
            $lhwxuser = Cookie::get('lh_wxuser');
            if (!$lhwxuser) $this->error('网页已过期，请重新打开');

            if (!Validate::regex($mobile, "^1\d{10}$")) $this->error('手机号格式错误');
            if (!Sms::check($mobile, $captcha, 'login')) $this->error('短信验证码错误');

            $wxuid = $this->io_aes_decrypt($lhwxuser);
            $wxuser = LihuaWxuser::get($wxuid);
            if (!$wxuser) $this->error('网页已过期，请重新打开');

            $user = User::getByMobile($mobile);
            if ($user) {
                $uid = $user->id;
                $user->nickname = $wxuser->nickname;
                $user->avatar   = $wxuser->avatar;
                $user->save();
            } else {
                $username = substr(md5($mobile), mt_rand(1,15), 10);
                $uid = $this->register($username, Random::alnum(8), $mobile, $wxuser->nickname, $wxuser->avatar);
                if (!$uid) $this->error('登录异常');
            }
            $wxuser->user_id = $uid;
            $wxuser->save();
            Cookie::set('lh_h5login', $this->io_aes_encrypt($uid . '|' . $mobile),
                ['expire' => 86400 * 30, 'secure' => true, 'httponly' => true]);
            Sms::flush($mobile, 'login');
            $this->success('OK');
        }
        $this->error('非法操作');
    }

    // 注册用户
    protected function register($username, $password, $mobile, $nickname = '', $avatar = '')
    {
        $ip = request()->ip();
        $time = time();

        $data = [
            'username'  => $username,
            'nickname'  => $nickname,
            'password'  => $password,
            'salt'      => Random::alnum(),
            'mobile'    => $mobile,
            'avatar'    => $avatar,
            'level'     => 1,
            'score'     => 0,
            'prevtime'  => $time,
            'logintime' => $time,
            'loginip'   => $ip,
            'jointime'  => $time,
            'joinip'    => $ip,
            'status'    => 'normal'
        ];
        $data['password'] = $this->getEncryptPassword($password, $data['salt']);

        Db::startTrans();
        try {
            $user = User::create($data);
            $uid = $user->id;
            Hook::listen("user_register_successed", $user);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
        return $uid;
    }

    // 获取微信用户信息
    protected function getWxUserInfo($access_token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $res = Http::get($url);
        $arr = json_decode($res, true);
        if (isset($arr['errcode'])) {
            $this->setError($arr['errmsg']);
            return false;
        }
        return $arr;
    }

    protected function setError($error = '')
    {
        $this->_error = $error;
    }

    protected function getError()
    {
        return $this->_error;
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    protected function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    /**
     * AES加密
     */
    protected function io_aes_encrypt($str, $key = 'ZzI4OGh6NXh5eg==', $iv = 'NTRob25nMTk4NWhhcmR5cw=====') {
        return base64_encode(
            openssl_encrypt(
                $str, 'aes-128-cbc',
                base64_decode($key), OPENSSL_RAW_DATA,
                base64_decode($iv)
            )
        );
    }

    /**
     * AES解密
     */
    protected function io_aes_decrypt($str, $key = 'ZzI4OGh6NXh5eg==', $iv = 'NTRob25nMTk4NWhhcmR5cw=====') {
        return openssl_decrypt(
            base64_decode($str), 'aes-128-cbc',
            base64_decode($key), OPENSSL_RAW_DATA,
            base64_decode($iv)
        );
    }
}
